package tech.aistar.day13;

import tech.aistar.day10.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/3/24 3:03 下午
 */
public class IOUtil<T> {

    public void writeObject2(List<T> list, String pathname){
//        List<T> oldList = readObject(pathname);
//        if(oldList!=null && oldList.size()>0){
//            list.addAll(oldList);
//        }
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(pathname))){
            out.writeObject(list);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeObject(List<T> list, String pathname){
        List<T> oldList = readObject(pathname);
        if(oldList!=null && oldList.size()>0){
            list.addAll(oldList);
        }
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(pathname))){
            out.writeObject(list);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<T> readObject(String pathname){
        List<T> list = null;
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(pathname))){
            list = (List<T>) in.readObject();
        } catch (FileNotFoundException e) {
            //e.printStackTrace();
            list = null;
        } catch (IOException e) {
            //e.printStackTrace();
            list = null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        Book b1 = new Book(5,"1005","西游记2",100.0d);
        Book b2 = new Book(6,"1006","三体2",100.0d);
        books.add(b1);
        books.add(b2);

        IOUtil<Book> bookIOUtil = new IOUtil<>();
        bookIOUtil.writeObject(books,"src/tech/aistar/day13/books.txt");

        List<Book> list = bookIOUtil.readObject("src/tech/aistar/day13/books.txt");
        if(null!=list && list.size()>0){
            for (Book book : list) {
                System.out.println(book);
            }
        }
    }
}
